package com.zxc.oj.ojcodesandbox;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
import com.github.dockerjava.api.command.StatsCmd;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.zxc.oj.ojcodesandbox.model.ExecuteCodeRequest;
import com.zxc.oj.ojcodesandbox.model.ExecuteCodeResponse;
import com.zxc.oj.ojcodesandbox.model.ExecuteMessage;
import com.zxc.oj.ojcodesandbox.model.JudgeInfo;
import com.zxc.oj.ojcodesandbox.utils.ProcessUtils;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class JavaDockerCodeSandbox extends JavaCodeSandboxTemple {

    private final static String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private final static String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private final static Long TIME_OUT = 1000L;
    //获取默认的Docker Client
    public static final DockerClient dockerClient = DockerClientBuilder.getInstance().build();
    public static final String IMAGE = "openjdk:8-alpine";


    public static void main(String[] args) {
        JavaDockerCodeSandbox sandbox = new JavaDockerCodeSandbox();
        ExecuteCodeRequest codeRequest = new ExecuteCodeRequest();
        codeRequest.setInputList(Arrays.asList("1 2", "3 4"));
        String code = ResourceUtil.readStr("./testCode/simpleComputeArge/Main.java", StandardCharsets.UTF_8);
        codeRequest.setLanguage("java");
        codeRequest.setCode(code);
        ExecuteCodeResponse response = sandbox.executeCode(codeRequest);
        System.out.println(response);

    }

    @Override
    public File saveCodeToFile(String code) {
        return super.saveCodeToFile(code);
    }

    @Override
    public ExecuteMessage compileFile(File userCodeFile) {
        return super.compileFile(userCodeFile);
    }

    @Override
    public List<ExecuteMessage> run(File userCodeFile, List<String> inputList) {

        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(IMAGE);
        //映射本地文件到容器中
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(100 * 1000 * 1000L);
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);
        //hostConfig.withSecurityOpts(Arrays.asList("seccomp="));
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));

        CreateContainerResponse containerResponse = containerCmd
                .withName("java-code-sandbox" + UUID.randomUUID())
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)
                .withReadonlyRootfs(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withAttachStderr(true)
                .withTty(true)
                .exec();
        String containerId = containerResponse.getId();

        System.out.println("containerId" + containerId);
        //启动容器
        dockerClient.startContainerCmd(containerId).exec();

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        ExecuteMessage executeMessage = new ExecuteMessage();
        final String[] message = {null};
        final String[] errorMessage = {null};
        final Object lock = new Object(); // 创建一个锁对象来控制同步
        for (String inputArgs : inputList) {
            //定时器
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            //docker exec java-code-sandbox java -cp /app Main 1 2
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .withCmd(cmdArray)
                    .exec();
            System.out.println("创建执行命令：" + execCreateCmdResponse);
            String execId = execCreateCmdResponse.getId();
            final boolean[] timeout = {true};
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    synchronized (lock) {
                        timeout[0] = false;
                        lock.notifyAll(); // 通知所有等待在lock对象上的线程
                    }
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errorMessage[0]);
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    System.out.println();
                    super.onNext(frame);
                }
            };


            final long[] maxMemory = {0L};

            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            statsCmd.exec(new ResultCallback<Statistics>() {

                @Override
                public void close() throws IOException {

                }

                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(Statistics statistics) {
                    Long usage = statistics.getMemoryStats().getUsage();
                    System.out.println("内存占用：" + usage);
                    maxMemory[0] = Math.max(maxMemory[0], usage);
                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }
            });


            try {
                stopWatch.start();
                dockerClient.execStartCmd(execId).exec(execStartResultCallback).awaitCompletion(TIME_OUT, TimeUnit.MICROSECONDS);
                synchronized (lock) {
                    while (timeout[0]) {
                        lock.wait(); // 在lock对象上等待，直到回调调用notifyAll/notify
                    }
                }
                // 确保在下一次迭代前重置状态
                message[0] = null;
                errorMessage[0] = null;
                stopWatch.stop();
                statsCmd.close();

            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            } finally {
                try {
                    execStartResultCallback.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setRunTime(stopWatch.getLastTaskTimeMillis());
            executeMessage.setMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }
        try {
            Thread.sleep(TIME_OUT * 10);
            dockerClient.removeContainerCmd(containerId).withForce(true).exec();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        return executeMessageList;
    }

    @Override
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        long maxTime = 0;//判断程序是否超时
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                response.setMessage(errorMessage);
                //用户代码执行错误
                response.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long runTime = executeMessage.getRunTime();
            if (runTime != null) {
                maxTime = Math.max(runTime, maxTime);
            }
        }
        //判断是否正常执行
        if (outputList.size() == executeMessageList.size()) {
            response.setStatus(1);
        }
        response.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory();
//        judgeInfo.setMessage();
        response.setJudgeInfo(judgeInfo);
        return response;
    }

    @Override
    public boolean delFile(File userCodeFile) {
        return super.delFile(userCodeFile);
    }

    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {
        List<String> inputList = request.getInputList();
        String language = request.getLanguage();
        String code = request.getCode();

        //保存用户代码到文件
        File userCodeFile = saveCodeToFile(code);
        //编译代码，得到class文件
        ExecuteMessage executeMessage = compileFile(userCodeFile);
        log.info("executeMessage:{}", executeMessage);
        //运行
        List<ExecuteMessage> executeMessages = run(userCodeFile, inputList);
        //清理文件
        boolean b = delFile(userCodeFile);
        if (!b) {
            log.error("删除文件失败，userCodeParentPath={}", userCodeFile.getParentFile().getAbsolutePath());
        }
        //封装响应
        return getOutputResponse(executeMessages);

    }

    /**
     * 获取错误响应
     * @param e
     * @return
     */
    public ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse response = new ExecuteCodeResponse();
        response.setOutputList(new ArrayList<>());
        response.setMessage(e.getMessage());
        //2 表示代码沙箱运行错误
        response.setStatus(2);
        response.setJudgeInfo(new JudgeInfo());

        return response;
    }
}
